package com.mini.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.mini.conditon.BusinessConditionNew;
import com.mini.config.CheckLogin;
import com.mini.config.UnLoginException;
import com.mini.constant.RedisKeyConst;
import com.mini.model.BusinessBaseInfo;
import com.mini.model.BusinessItemInfo;
import com.mini.req.BusinessBaseInfoNew;
import com.mini.req.BusinessBaseInfoNewList;
import com.mini.service.BusinessBaseService;
import com.mini.service.BusinessTraditionChanceService;
import com.mini.service.MiniAdminService;
import com.mini.util.CalendarUtil;
import com.mini.vo.BusinessResult;
import com.mini.vo.CommonResultMessage;
import com.mini.vo.PageResultVO;
import com.mini.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhangxiaobin
 * @title: MiniLessonBaseControler
 * @description: TODO
 * @date 2019/10/2711:36
 */
@RestController
@RequestMapping("/business")
@Api(tags = "传统站点相关接口")
@Slf4j
public class BusinessControler extends BaseController {

    @Value("${count.business.data.cachetime}")
    private Long cacheTime;

    @Value("${test.minilessonsite}")
    private Long minilessonMax;
    @Value("${test.minilessonsite.min}")
    private Long minilessonMin;

    @Autowired
    private BusinessBaseService businessBaseService;


    @Autowired
    HttpServletRequest httpServletRequest;


    @Autowired
    private MiniAdminService miniAdminService;

    @Autowired
    private BusinessTraditionChanceService businessTraditionChanceService;






    @CheckLogin
    @ApiOperation(value = "批量创建小课站点", notes = "批量创建小课站点")
    @PostMapping("/lessonsite/batch/add")
    public BusinessResult<BusinessBaseInfo> newLessonSite(@ApiParam(value = "token", required = true) @RequestHeader String Authorization,
                                                          @RequestBody BusinessBaseInfoNewList businessBaseInfoNewList){

        log.info("创建小课站点参数：{}",businessBaseInfoNewList);
        List<BusinessBaseInfoNew> businessBaseInfoNewLists = businessBaseInfoNewList.getBusinessBaseInfoList();

        List<String> errorMsgs = new ArrayList<>();
        if (null == businessBaseInfoNewLists || businessBaseInfoNewLists.size() == 0) {
            return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR, "请求参数为空");
        }
        UserVO loginUser = getLoginUser(Authorization);
        BusinessResult<BusinessBaseInfo> businessBaseInfoNew = businessBaseService.getBusinessBaseInfoBusinessResult(businessBaseInfoNewLists, errorMsgs, loginUser.getId());
        if (businessBaseInfoNew != null) return businessBaseInfoNew;
        return BusinessResult.createSuccessInstance("success");

    }



    //批量上传
    @CheckLogin
    @ApiOperation(value = "个人上传传统-飞天系统Excel模版")
    @PostMapping(value = "/_self/_uploadChuanTongFT", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public BusinessResult uploadChuanTongFTReply(@ApiParam(value = "Authorization", required = true) @RequestHeader String Authorization,
                                               @RequestParam("file") MultipartFile file) throws Exception {
        try {
            String originalFilename = file.getOriginalFilename();
            InputStream inputStream = file.getInputStream();
            Workbook workbook = getWorkbook(inputStream, originalFilename);
            if (null == workbook) {
                return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR, "excel为空");
            }
            Sheet sheet = workbook.getSheetAt(0);
            if (null == sheet) {
                return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR, "excel sheet为空");
            }
            int lastRowNum = sheet.getLastRowNum();
            List<JSONObject> arrayList = Lists.newArrayList();
            for (int i = 1; i <= lastRowNum; i++) {
                try {
                    JSONObject jsonObject = new JSONObject();
                    Row row = sheet.getRow(i);
                    Cell cell = row.getCell(0);
                    try {
                        String stringCellValue = cell.getStringCellValue();
                        if (stringCellValue.length() >= 60) {
                            throw new RuntimeException("参数异常"+stringCellValue);
                        }
                        jsonObject.put("miniLessonName", stringCellValue);
                    } catch (Exception e) {
                        log.error("miniLessonName异常", e.getMessage());
                    }
                    Double numericCellValue = null;
                    try {
                        cell = row.getCell(1);
                        numericCellValue = cell.getNumericCellValue();
                        log.debug("numericCellValue={}", numericCellValue);
                        if(numericCellValue > 0.0){
                            if (numericCellValue >= minilessonMax || numericCellValue < minilessonMin) {
                                throw new RuntimeException("参数异常"+numericCellValue);
                            }
                            jsonObject.put("xingtu_site", numericCellValue.intValue());
                        }else {
                            jsonObject.put("xingtu_site", "");
                        }


                    } catch (Exception e) {
                        log.error("xingtu_site异常", e.getMessage());
                    }

                    arrayList.add(jsonObject);
                } catch (Exception e) {
                    log.error("个人上传Excel模版error", e.getMessage());
                }
            }
            return BusinessResult.createSuccessInstance(arrayList);
        } catch (Exception e) {
            log.error("个人从Excel模版异常", e);
            return BusinessResult.createInstance(CommonResultMessage.ERROR, e.getMessage());
        }
    }

    //批量上传
    @CheckLogin
    @ApiOperation(value = "个人上传传统-星图Excel模版")
    @PostMapping(value = "/_self/_uploadChuanTong", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public BusinessResult uploadChuanTongReply(@ApiParam(value = "Authorization", required = true) @RequestHeader String Authorization,
                                               @RequestParam("file") MultipartFile file) throws Exception {
        try {
            String originalFilename = file.getOriginalFilename();
            InputStream inputStream = file.getInputStream();
            Workbook workbook = getWorkbook(inputStream, originalFilename);
            if (null == workbook) {
                return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR, "excel为空");
            }
            Sheet sheet = workbook.getSheetAt(0);
            if (null == sheet) {
                return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR, "excel sheet为空");
            }
            int lastRowNum = sheet.getLastRowNum();
            List<JSONObject> arrayList = Lists.newArrayList();
            for (int i = 1; i <= lastRowNum; i++) {
                try {
                    JSONObject jsonObject = new JSONObject();
                    Row row = sheet.getRow(i);
                    Cell cell = row.getCell(0);
                    try {
                        String stringCellValue = cell.getStringCellValue();
                        if (stringCellValue.length() >= 60) {
                            throw new RuntimeException("参数异常"+stringCellValue);
                        }
                        jsonObject.put("miniLessonName", stringCellValue);
                    } catch (Exception e) {
                        log.error("miniLessonName异常", e.getMessage());
                    }
                    Double numericCellValue = null;
                    try {
                        cell = row.getCell(1);
                        numericCellValue = cell.getNumericCellValue();
                        log.debug("numericCellValue={}", numericCellValue);
                        if(numericCellValue > 0.0){
                            if (numericCellValue >= minilessonMax || numericCellValue < minilessonMin) {
                                throw new RuntimeException("参数异常"+numericCellValue);
                            }
                            jsonObject.put("xingtu_site", numericCellValue.intValue());
                        }else {
                            jsonObject.put("xingtu_site", "");
                        }


                    } catch (Exception e) {
                        log.error("xingtu_site异常", e.getMessage());
                    }

                    arrayList.add(jsonObject);
                } catch (Exception e) {
                    log.error("个人上传Excel模版error", e.getMessage());
                }
            }
            return BusinessResult.createSuccessInstance(arrayList);
        } catch (Exception e) {
            log.error("个人从Excel模版异常", e);
            return BusinessResult.createInstance(CommonResultMessage.ERROR, e.getMessage());
        }
    }





    @CheckLogin
    @ApiOperation(value = "获取我的小课站点列表，分页", notes = "获取我的小课站点列表，分页")
    @PostMapping("/pageNew")
    public BusinessResult<PageResultVO<BusinessBaseInfo>> pageNew(@ApiParam(value = "token", required = true) @RequestHeader String Authorization,
                                                                  @ApiParam(value = "查询条件", required = true) @RequestBody BusinessConditionNew businessCondition){
        long startTime = System.currentTimeMillis();
        checkPageParams(businessCondition);
        businessCondition.setSortColumn("miniLessonId");
        Long loginUserId = this.miniAdminService.getLoginUserId(Authorization);
        if(loginUserId == null){
            throw new UnLoginException("未登录！");
        }else {
            businessCondition.setCreateUserId(loginUserId);
        }
        log.info("businessCondition ={}", JSONObject.toJSONString(businessCondition));
        PageResultVO<BusinessBaseInfo> page = businessBaseService.pageNew(businessCondition);
        String baseKey = RedisKeyConst.getBusinessNewFlag("base", loginUserId);
        Set members = redisTemplate.opsForSet().members(baseKey);
        log.info("members={}", members);
        List<BusinessItemInfo> itemInfoList = businessTraditionChanceService.getAllItemInfo();
        log.info("itemList={}",JSONObject.toJSONString(itemInfoList));
        Map<Integer,String> itemmap = itemInfoList.stream().collect(Collectors.toMap(BusinessItemInfo::getId, BusinessItemInfo::getItemName));
        for (BusinessBaseInfo businessBaseInfo : page.getRows()) {
            if(businessBaseInfo != null && businessBaseInfo.getSiteItem() != null){
                businessBaseInfo.setSiteItemName(itemmap.get(businessBaseInfo.getSiteItem()));
            }
            Iterator<Integer> iterator = members.iterator();
            while (iterator.hasNext()) {
                Integer next = iterator.next();
                if (next.longValue() == businessBaseInfo.getMiniLessonId().longValue()) {
                    log.debug("members 2===={}", businessBaseInfo.getMiniLessonId());
                    businessBaseInfo.setNewFlag((byte) 1);
                }
            }
        }
        long endTime = System.currentTimeMillis();
        log.info("小课站点列表 pageSize={} cost={}",businessCondition.getPageSize(),endTime-startTime);
        return BusinessResult.createSuccessInstance(page);
    }

    public static void main(String[] args) {
        Set<Integer> longs = new HashSet<>();
        longs.add(100000883);
        BusinessBaseInfo businessBaseInfo = new BusinessBaseInfo();
        businessBaseInfo.setMiniLessonId(100000883L);
        for (Integer m : longs) {
            if (m.longValue() == businessBaseInfo.getMiniLessonId().longValue()) {
                System.out.println(m);
            }
        }
    }


    @ApiOperation(value = "获取小课业务信息", notes = "获取小课业务信息")
    @GetMapping("/businessInfo")
    public BusinessResult<BusinessBaseInfo> businessInfo(@ApiParam(value = "签名信息",required = true)@RequestHeader String sig,
                                                         @ApiParam(value = "小课业务id",required = true)@RequestParam Long businessId){
        if(!(checkSign(sig))){
            return BusinessResult.createInstance(CommonResultMessage.SIGN_ERROR);
        }
        BusinessBaseInfo businessBaseInfo = businessBaseService.getByMiniLessonId(businessId);
        return BusinessResult.createSuccessInstance(businessBaseInfo);
    }


    @CheckLogin
    @ApiOperation(value = "获取我的当日小课站点列表", notes = "获取我的当日小课站点列表")
    @GetMapping("/todaySiteList")
    public BusinessResult<List<BusinessBaseInfo>> todaySiteList(@ApiParam(value = "token", required = true) @RequestHeader String Authorization
    ){
        BusinessConditionNew businessCondition = new BusinessConditionNew();
        businessCondition.setBeginTime(CalendarUtil.getShortDateString(new Date()));
        Long loginUserId = this.miniAdminService.getLoginUserId(Authorization);
        if(loginUserId == null){
            throw new UnLoginException("未登录！");
        }else {
            businessCondition.setCreateUserId(loginUserId);
        }
        List<BusinessBaseInfo> page = businessBaseService.nowNewSiteList(businessCondition);

        return BusinessResult.createSuccessInstance(page);
    }








}
